// Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use log::error;
use maestro_derive::MsgTag;
use ohmw_derive::{BorrowDecode, Decode, Encode};

#[derive(BorrowDecode)]
pub struct PutFileReq<'a> {
    pub file_path: &'a str,
    pub content: &'a [u8],
}

#[derive(Encode, Decode, MsgTag)]
#[msg_tag(case = "snake_case")]
pub struct PutFileRet {
    pub file_path: String,
    pub success: bool,
}

pub async fn put_file(req: PutFileReq<'_>) -> PutFileRet {
    if let Err(e) = tokio::fs::write(req.file_path, req.content).await {
        error!("Failed to write file {}: {}", req.file_path, e);
        return PutFileRet {
            file_path: req.file_path.to_string(),
            success: false,
        };
    }

    PutFileRet {
        file_path: req.file_path.to_string(),
        success: true,
    }
}
